package NG::Sys::Datetime;
use strict;
use warnings;
use utf8;

require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(
unixtime2timestamp
timestamp2unixtime
unixtime2datetime
unixtime2ydm
unixtime2hms
second2text
next_day
prev_day
);
require Time::Local;

sub timestamp2unixtime {
	my $stamp = shift;
	if($stamp =~ /^(\d{4})\D?(\d{2})\D?(\d{2})\D?(\d{2})\D?(\d{2})\D?(\d{2})$/){
		unless($1 + $2 + $3){
			return 0;
		}
		my $t = Time::Local::timelocal($6,$5,$4,$3,$2-1,$1-1900);
		return $t;
	}
	return time();
}
sub unixtime2timestamp {
	my $time = shift || time;
	my @t = localtime($time);
	return sprintf "%04d%02d%02d%02d%02d%02d",$t[5]+1900,$t[4]+1,$t[3],$t[2],$t[1],$t[0];
}
sub unixtime2datetime {
	my $time = shift || time;
	my @t = localtime($time);
	return sprintf "%04d-%02d-%02d %02d:%02d:%02d",$t[5]+1900,$t[4]+1,$t[3],$t[2],$t[1],$t[0];
}
sub unixtime2ydm {
	my $time = shift || time;
	my @t = localtime($time);
	return sprintf "%04d-%02d-%02d",$t[5]+1900,$t[4]+1,$t[3];
}
sub unixtime2hms {
	my $time = shift || time;
	my @t = localtime($time);
	return sprintf "%02d:%02d:%02d",$t[2],$t[1],$t[0];
}
sub second2text {
	my $s = $_[0] % 60;
	my $m = int($_[0] / 60);
	my $h = int($m / 60);
	$m = $m % 60;
	return sprintf("%d:%02d:%02d",$h,$m,$s);
}
sub next_day {
	my $time = shift || time;
	my @t = localtime($time);
	return Time::Local::timelocal(23,59,59,$t[3],$t[4],$4[5]) + 1;
}
sub prev_day {
	my $time = shift || time;
	my @t = localtime($time);
	return Time::Local::timelocal(0,0,0,$t[3],$t[4],$4[5]) - 1;
}
1;
